package source.javadog.mysource;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * Author : manyu
 * Date: 2018/9/9 17:27
 * Description:
 */
public class MyDataSources {

    public static final String JDBC_CONNECTIONS_LIMIT = "javax.persistence.connections.limit";

    public static final String JDBC_CONTAIN_SQLTEMPLATE = "javax.persistence.contain.sqltemplate";

    public static final String JDBC_NOTCONTAIN_SQLTEMPLATE = "javax.persistence.notcontain.sqltemplate";

    public static final String JDBC_TABLENOTEXIST_SQLSTATES = "javax.persistence.tablenotexist.sqlstates";

    public static final String JDBC_TABLECOPY_SQLTEMPLATE = "javax.persistence.tablecopy.sqltemplate";

    public static final String JDBC_ENCODING = "javax.persistence.jdbc.encoding";

    public static final String DB_DATASOURCE = "datasource";

    public static final String JDBC_URL = "url";

    public static final String JDBC_USER = "user";

    public static final String JDBC_PWD = "password";

    public static final String JDBC_DRIVER = "driver";


    public static MyDataSource createDataSource(final String unitName, URL dbxml) throws IOException {
        InputStream in = dbxml == null ? null : dbxml.openStream();
        Map<String, String> dbMap = loadDbProp(unitName, in);

        String impl = dbMap.get(DB_DATASOURCE);
        if (impl == null) impl = MyDataJdbcSource.class.getName();

        if (MyDataJdbcSource.class.getName().equals(impl)) return new MyDataJdbcSource(dbMap);

        //todo 为毛返回null，不是指定的操作类型，不然为毛需要指定DB_DATASOURCE的类型
        return null;
    }


    /**
     * 读取数据库配置文件
     */
    private static Map<String,String> loadDbProp(final String unitName, final InputStream in) throws IOException {
        Properties properties = new Properties();
        properties.load(in);
        in.close();

        final Map<String, String> dbMap = new LinkedHashMap();
        dbMap.put(JDBC_URL,properties.getProperty(unitName + "." + JDBC_URL));
        dbMap.put(JDBC_DRIVER,properties.getProperty(unitName + "." + JDBC_DRIVER));
        dbMap.put(JDBC_USER,properties.getProperty(unitName + "." + JDBC_USER));
        dbMap.put(JDBC_PWD,properties.getProperty(unitName + "." + JDBC_PWD));
        dbMap.put(DB_DATASOURCE,properties.getProperty(unitName + "." + DB_DATASOURCE));

        return dbMap;
    }
}
